use model_graph_types::container::workflow::{
    WorkflowDocument, WorkflowDocumentReadeOptions, WorkflowDocumentReader,
};
use std::fs::read_to_string;
use std::path::PathBuf;

#[derive(Debug, Default)]
pub struct WorkflowDocumentJsonReader {}

#[async_trait::async_trait]
impl WorkflowDocumentReader for WorkflowDocumentJsonReader {
    /// 根据数据库获取到元数据
    async fn read_from_json_file(
        &self,
        file_path: &String,
        options: WorkflowDocumentReadeOptions,
    ) -> anyhow::Result<WorkflowDocument> {
        let json = read_to_string(PathBuf::from(file_path))?;
        self.read_from_string(&json, options).await
    }

    async fn read_from_string(
        &self,
        json_string: &String,
        _options: WorkflowDocumentReadeOptions,
    ) -> anyhow::Result<WorkflowDocument> {
        let document: WorkflowDocument = serde_json::from_str(json_string.as_str())
            .map_err(|err| anyhow::anyhow!("JSON解析失败:{}\n{}", err, json_string))?;

        Ok(document)
    }
}
